package com.sfzd5.mistakesbook;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.sfzd5.mistakesbook.databinding.ActivityMainBinding;
import com.sfzd5.mistakesbook.db.DBHelper;
import com.sfzd5.mistakesbook.db.Exam;
import com.sfzd5.mistakesbook.db.Knowledge;
import com.sfzd5.mistakesbook.db.Student;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    enum FragmentType {STUDENT, EXAM, KNOWLEDGE}

    private ActivityMainBinding binding;

    MistakesApplication app;

    String[] tabNames = {"测试", "学生", "知识点"};
    List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        app = (MistakesApplication) getApplication();

        binding.viewPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        fragments = new ArrayList<>();
        fragments.add(new ItemFragment(FragmentType.EXAM));
        fragments.add(new ItemFragment(FragmentType.STUDENT));
        fragments.add(new ItemFragment(FragmentType.KNOWLEDGE));

        binding.viewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                Fragment fragment = fragments.get(position);
                return fragment;
            }

            @Override
            public int getItemCount() {
                return fragments.size();
            }
        });

        binding.viewPager.setOffscreenPageLimit(3);

        new TabLayoutMediator(binding.tabLayout,
                binding.viewPager,
                true,
                true,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        tab.setText(tabNames[position]);
                    }
                }
        ).attach();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        for(Fragment fragment : fragments){
            ItemFragment itemFragment = (ItemFragment) fragment;
            itemFragment.adapter.notifyDataSetChanged();
        }
    }

    public static class ItemFragment extends Fragment {

        public FragmentType fragmentType;
        ListView lv;
        FloatingActionButton fab;
        ArrayList items;
        ArrayAdapter adapter;

        public ItemFragment(FragmentType fragmentType) {
            this.fragmentType = fragmentType;
        }

        InputTextDialog inputTextDialog;

        MainActivity mainActivity;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View root = inflater.inflate(R.layout.fragment_exam, container);
            lv = root.findViewById(R.id.lv);
            fab = root.findViewById(R.id.fab);
            mainActivity = (MainActivity) getActivity();
            inputTextDialog = new InputTextDialog(mainActivity);
            if (fragmentType == FragmentType.EXAM) {
                items = mainActivity.app.examList;
            } else if (fragmentType == FragmentType.STUDENT) {
                items = mainActivity.app.studentList;
            } else if (fragmentType == FragmentType.KNOWLEDGE) {
                items = mainActivity.app.knowledgeList;
            }

            //添加
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    inputTextDialog.showInputDialog("请输入名称", new InputTextDialogResultInterface() {
                        @Override
                        public void result(String result) {
                            String nm = result;
                            try {
                                if (fragmentType == FragmentType.EXAM) {
                                    Exam exam = new Exam();
                                    exam.exam = nm;
                                    DBHelper.getInstance(getContext()).getExamDao().create(exam);
                                    items.add(0, exam);
                                    //mainActivity.app.examList.add(0, exam);
                                } else if (fragmentType == FragmentType.STUDENT) {
                                    Student student = new Student();
                                    student.name = nm;
                                    student.grade = ((MistakesApplication) getActivity().getApplication()).readGrade();
                                    DBHelper.getInstance(getContext()).getStudentDao().create(student);
                                    items.add(0, student);
                                    //mainActivity.app.studentList.add(0, student);
                                } else if (fragmentType == FragmentType.KNOWLEDGE) {
                                    Knowledge knowledge = new Knowledge();
                                    knowledge.knowledge = nm;
                                    DBHelper.getInstance(getContext()).getKnowledgeDao().create(knowledge);
                                    items.add(0, knowledge);
                                    //mainActivity.app.knowledgeList.add(0, knowledge);
                                }
                                adapter.notifyDataSetChanged();
                            } catch (SQLException throwables) {
                                throwables.printStackTrace();
                            }
                        }
                    });
                }
            });
            adapter = new ArrayAdapter<Object>(getContext(), android.R.layout.simple_list_item_1, items);
            lv.setAdapter(adapter);

            //打开
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(getActivity(), MistakesActivity.class);
                    intent.putExtra("StartType", fragmentType.name());
                    intent.putExtra("StartData", new Gson().toJson(items.get(i)));
                    startActivity(intent);
                }
            });

            /*
            //长按删除
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                    return false;
                }
            });
            */
            return root;
        }
    }
}